package com.xxl.job.executor.service.jobhandler;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.RealNameAuth;
import com.ruoyi.bizsys.domain.UserFeedback;
import com.ruoyi.bizsys.mapper.RealNameAuthMapper;
import com.ruoyi.bizsys.service.IUserFeedbackService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.config.EmailConfig;
import com.ruoyi.common.config.EmailRouteConfig;
import com.ruoyi.common.constant.EmailConstants;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.EmailUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.vo.EmailVo;
import com.ruoyi.sms.common.Constants;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.utils.EmailsTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发送用户反馈邮件  每天执行一次
 */
@Slf4j
@AllArgsConstructor
@Component
public class SendFeedbackEmailJob {

    @Autowired
    private IUserFeedbackService userFeedbackService;

    @Autowired
    private RealNameAuthMapper realNameAuthMapper;

    @Autowired
    private EmailRouteConfig emailRouteConfig;

    @Autowired
    private SysConfigServiceImpl sysConfigService;

    @XxlJob("sendFeedbackEmailJobHandler")
    public void send() {
        XxlJobHelper.log("用户反馈邮件发送任务 Start >>>>>>>>>>");

        // 查询出来当天 状态正常 没有发送邮件的反馈记录
        List<UserFeedback> userFeedbacks = userFeedbackService.list(new QueryWrapper<UserFeedback>().select("id", "user_id", "email", "operation_type").eq("is_send", 0).eq("state", Integer.parseInt(BizConstants.BIZ_STATUS_1)));
        if (CollectionUtils.isEmpty(userFeedbacks)) {
            throw new BusinessException("发送的邮箱任务没有查询出来结果");
        }

        // 邮件标题
        String subject = sysConfigService.selectConfigByKey("subject");

        // 收集要更改状态的userid
        ArrayList<String> userIds = new ArrayList<>();
        for (int i = 0; i < userFeedbacks.size(); i++) {
            UserFeedback feedback = userFeedbacks.get(i);
            String email = feedback.getEmail();
            if (StringUtils.isBlank(email)) {
                continue;
            }

            //  邮箱校验  如果失败备注信息 更改状态
            if (!isEmail(email)) {
                feedback.setRemark("邮箱地址为：" + email + ",邮箱格式错误");
                feedback.setState(Integer.parseInt(Constants.BIZ_STATUS_0));
                userFeedbackService.updateByUserId(feedback);
                continue;
            }

            // 如果弹窗类型是授信拒绝或者是提现拒绝 查询出来last name
            String lastName = null;
            String operationType = feedback.getOperationType();
            if (StringUtils.equalsAny(operationType, EmailConstants.CREDIT_REJECTION, EmailConstants.WITHDRAWAL_REJECTION)) {
                RealNameAuth realNameAuth = realNameAuthMapper.selectOne(new QueryWrapper<RealNameAuth>().select("last_name").eq("user_id", feedback.getUserId()).eq("state", BizConstants.BIZ_STATUS_1));
                if (realNameAuth == null) {
                    log.debug("实名信息非正常状态，不发邮件，跳过");
                    continue;
                }

                lastName = realNameAuth.getLastName();
            }

            // 根据弹窗的类型  调用发送邮件接口
            // 实名失败窗口
            // 邮件模板
            String emailsContent = null;
            switch (operationType) {
                case EmailConstants.REAL_FAILED:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailRealFail());
                    break;
                case EmailConstants.CREDIT_REJECTION:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailCreditRejection()).replace("{LastName}", lastName);
                    break;
                case EmailConstants.WITHDRAWAL_REJECTION:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailWithdrawalRejection()).replace("{LastName}", lastName);
                    break;
                case EmailConstants.CARD_FAILED:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailCardFailed());
                    break;
                case EmailConstants.WITHDRAWAL_FAILED:
                    emailsContent = EmailsTemplate.readEmailTemplate(emailRouteConfig.getBaseRoute() + emailRouteConfig.getEmailWithdrawalFailed());
                    break;
                default:
                    throw new BusinessException(RspEnmu.EMAIL_TYPE_NOEXIST);
            }
            try {
                EmailVo emailVo = EmailVo.builder()
                        .subject(subject)
                        .cc(new String[]{EmailConfig.getFeedBackAddress()})
                        .addressees(new String[]{email})
                        .feedBackEmailParam(emailsContent)
                        .build();
                String result = EmailUtils.sendfeedbackMailParameterAssemblyEmail(emailVo);
                JSONObject resultJson = JSONObject.parseObject(result);
                if ("200000".equals(resultJson.getString("code"))) {
                    userIds.add(feedback.getUserId());
                }
            } catch (Exception e) {
                log.error("调用发送邮件接口异常 >>>>>>>>>> ", e);
            }
        }

        // 批量一千条修改发送状态
        ArrayList<String> batchList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userIds)) {
            for (int i = 0; i < userIds.size(); i++) {
                batchList.add(userIds.get(i));
                if ((i + 1) % 1000 == 0 || i == userIds.size() - 1) {
                    userFeedbackService.updateBatchByUserId(batchList);
                    batchList.clear();
                }
            }
        }

        XxlJobHelper.log("用户反馈邮件发送任务 End >>>>>>>>>>");
    }

    public boolean isEmail(String email) {
        if (null == email || "".equals(email)) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(email);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

}
